package config

import (
	"os"
	"time"

	"gitee.com/ironCoffers/goHelper/config/base"
)

type hotConfig struct {
	config         *defaultConfig
	interval       int64
	lastModifyTime int64
	notifyer       base.Notifyer
}

func (hc *hotConfig) reload() {
	if hc.interval <= 0 {
		return
	}
	interval := time.Duration(hc.interval) * time.Second
	ticker := time.NewTicker(interval)
	for _ = range ticker.C {
		func() {
			f, err := os.Open(hc.config.fileName)
			if err != nil {
				return
			}

			defer f.Close()
			fileInfo, err := f.Stat()
			if err != nil {
				return
			}
			curModTime := fileInfo.ModTime().Unix()
			if curModTime > hc.lastModifyTime {
				if err := hc.config.parse(); err == nil {
					hc.lastModifyTime = curModTime
					hc.notifyer(hc.config)
				}
			}
		}()
	}
}

func (hc *hotConfig) GetInt(key string) (int, error) {
	return hc.config.GetInt(key)
}

func (hc *hotConfig) GetIntDefault(key string, defaultInt int) int {
	return hc.config.GetIntDefault(key, defaultInt)
}

func (hc *hotConfig) GetString(key string) (string, error) {
	return hc.config.GetString(key)
}

func (hc *hotConfig) GetStringDefault(key, defaultString string) string {
	return hc.config.GetStringDefault(key, defaultString)
}

func (hc *hotConfig) GetMap(key string) (map[string]interface{}, error) {
	return hc.config.GetMap(key)
}

func (hc *hotConfig) GetInterface(key string) (interface{}, error) {
	return hc.config.GetInterface(key)
}

func HConfig(fileName string, notifyer base.Notifyer) (base.BaseConfig, error) {
	dc := &defaultConfig{
		fileName: fileName,
	}
	err := dc.parse()
	if err != nil {
		return nil, err
	}
	hc := &hotConfig{
		config:   dc,
		notifyer: notifyer,
		interval: 10,
	}
	go hc.reload()
	return hc, nil
}
